package com.zl.service.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

import com.zl.domain.Query;
import com.zl.util.Page;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.zl.dao.BaseDao;
import com.zl.service.BaseService;

@Service
@SuppressWarnings("unchecked")
public class BaseServiceImpl<T> implements ApplicationContextAware,
        BaseService<T> {

    private ApplicationContext context;
    private BaseDao<T> dao;

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        this.context = context;
        ParameterizedType pt = (ParameterizedType) this.getClass()
                .getGenericSuperclass();
        Class<T> clazz = (Class<T>) pt.getActualTypeArguments()[0];
        dao = (BaseDao<T>) context.getBean(clazz.getSimpleName().toLowerCase()
                + "Dao");
    }


    @Override
    public int insert(T model) {
        return model == null ? 0 : dao.insert(model);
    }

    @Override
    public List<T> selectByModel(T model) {
        return model == null ? null : dao.selectByModel(model);
    }

    @Override
    public int delete(T model) {
        return model == null ? 0 : dao.delete(model);
    }

    @Override
    public int update(T model) {
        return model == null ? 0 : dao.update(model);
    }

    @Override
    public int count(T model) {
        return model == null ? 0 : dao.count(model);
    }

    @Override
    public int deleteByIds(List<Integer> ids, T model) {
        return ids.size() > 0 ? dao.deleteByIds(ids, model) : 0;
    }

    @Override
    public int updateByIds(List<Integer> ids, T model) {
        return ids.size() > 0 ? dao.updateByIds(ids, model) : 0;
    }

    @Override
    public List<T> findAll(T model) {
        return dao.findAll(model);
    }

    @Override
    public List<T> findAll() {
        return dao.findAll();
    }

    @Override
    public Page<Map<String, Object>> page(Query query) {
        int currentPage = query.getCurrentPage(), pageSize = query
                .getPageSize();
        query.setCurrentPage((currentPage - 1) * pageSize);
        return new Page<Map<String, Object>>(currentPage, pageSize,
                dao.page(query), dao.pageCount(query));
    }

    @Override
    public T findByModel(T model) {
        return dao.findByModel(model);
    }
}
